<?php

/**
 * 商品模型
 */
class WapGoodsModel extends BaseModel {

    public function tableName() {
        return '{{goods}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Goods the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 获取商品数据集合
     * @param CDbCriteria $where 可以是查询表达式（数组），也可以是 CDbCriteria 对象，也可以是 SQL的WHERE部分字符串
     * @param type $num 显示数量
     * @param type $page 传入数值类型表示启用分页，分页对象在 返回的数组下标1
     * @param type $order 排序方式
     * @param type $orderRandom 是否进行特定随机排序，默认是
     * @param type $cacheKey 是否进行缓存，如果需要，传入缓存KEY
     * @return array
     */
    public function getGoodsList($where = false, $num = 99, $page = false, $order = 'default', $orderRandom = true, $cacheKey = '') {
        if (!empty($cacheKey)) {
            $return = Yii::app()->cache->get($cacheKey);
            if (!empty($return)) {
                return $return;
            }
        }
        if (is_object($where) && $where instanceof CDbCriteria) {
            $criteria = $where;
        } else if (is_array($where)) {
            $criteria = $this->where($where);
        } else if (is_string($where)) {
            $criteria = new CDbCriteria();
            $criteria->addCondition($where);
        } else {
            $criteria = new CDbCriteria();
        }
        //排序
        switch ($order) {
            //以添加时间降序
            case 'add_time':
                $criteria->order = 'add_time DESC,listorder DESC';
                $orderRandom = false;
                break;
            //以活动价格冲倒序
            case 'promo_price':
                $criteria->order = "promo_price ASC";
                $orderRandom = false;
                break;
            //以销量降序
            case 'sales':
                $criteria->order = "sales DESC";
                $orderRandom = false;
                break;
            //以推荐降序
            case 'is_best':
                $criteria->order = "is_best DESC,listorder DESC";
                $orderRandom = false;
                break;
            case 'default':
                $criteria->order = 'start_time DESC ,listorder DESC';
                $orderRandom = true;
                break;
            //默认以上架时间降序
            default:
                $criteria->order = $order;
        }
        //是否分页
        if ($page !== false && $num > 0) {
            $count = $this->count($criteria);
            $pager = new CPagination($count);
            $pager->pageSize = $num;
            if ($order) {
                $pager->params = array('sort' => $order);
            }
            //设置当前分页号
            $pager->setCurrentPage($page - 1 < 0 ? 0 : $page - 1);
            $pager->applyLimit($criteria);
        } else if ($num > 0) {
            //数量
            $criteria->limit = $num;
        }
        //缓存获取
        $dataList = $this->findAll($criteria);
        $cats = CategoryModel::model()->getList();
        $return = array();
        foreach ($dataList as $rs) {
            $return[$rs->goods_id] = self::convertGood($rs, $cats);
        }
        //打乱排序
        if ($orderRandom) {
            $return = $this->orderRandomForStartTime($return);
            //$this->getIds_array($return);
        }
        if ($page !== false && $num > 0) {
            $return = array($return, $pager);
        }
        if ($cacheKey) {
            $status = Yii::app()->cache->set($cacheKey, $return, 600);
        }
        return $return;
    }

    /**
     * 根据id数组 查询goods表
     * 
     */
    public function getGoodsbyids($ids_array) {
        $num = Yii::app()->params->page_size['sault_index'];
        $order = "default";
        if (empty($ids_array))
            return '';
        $where = array(
            'goods_id' => array('IN', $ids_array),
        );
        $criteria = $this->where($where);
        $criteria->order = 'start_time DESC ,listorder DESC';
        $dataList = $this->findAll($criteria);
        foreach ($dataList as $rs) {
            $return[$rs->goods_id] = self::convertGood($rs, $cats);
        }

        $return = $this->orderRandomForStartTime($return);
        return $return;
    }

    //获取wap首页需要显示的商品
    public function getWapHomeGoods($num = 99, $cache = '', $order = "default") {
        $time = time();
        $page = (int) $_GET['page'];
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'level' => 1,
            'status' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
        );
        return $this->getGoodsList($where, $num, $page, $order, false, $cache);
    }

    //9.9专区
    public function getJJGoods($num = 99, $cache = '', $order = "default") {
        $time = time();
        $page = (int) $_GET['page'];
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'level' => 1,
            'status' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
            'promo_price' => array('LT', 10),
        );
        return $this->getGoodsList($where, $num, $page, $order, true, $cache);
    }

    //京东专区
    public function getJdGoods($num = 99, $cache = '', $order = "default") {
        $time = time();
        $page = (int) $_GET['page'];
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'item_type' => 11,
            'status' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
        );
        return $this->getGoodsList($where, $num, $page, $order, true, $cache);
    }

    //天猫专区
    public function getTmallGoods($num = 99, $cache = '', $order = "default") {
        $time = time();
        $page = (int) $_GET['page'];
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'item_type' => 1,
            'status' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
        );
        return $this->getGoodsList($where, $num, $page, $order, true, $cache);
    }

    //秋冬新款专区
    public function getRecommendGoods($num = 99, $cache = '', $order = "default") {
        $time = time();
        $page = (int) $_GET['page'];
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'level' => 1,
            'status' => 1,
            'is_best' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
        );
        return $this->getGoodsList($where, $num, $page, $order, false, $cache);
    }

    //获取各栏目下的商品数据(1:女装 2:男装 3:母婴....)
    public function getCatGoods($num = 99, $cache = '', $order = "default") {
        $time = time();
        $cid = (int) $_GET['cid'];
        $page = (int) $_GET['page'];
        $max_start_time = strtotime(date('Y-m-d', $time)) + 86400;
        $where = array(
            'status' => 1,
            'start_time' => array('LT', $max_start_time),
            'end_time' => array('GT', $time),
        );
        if ($cid > 0) {
            $where['cat_id'] = $cid;
        }
        return $this->getGoodsList($where, $num, $page, $order, true, $cache);
    }

    protected static function convertGood($good, $cats) {
        $time = $_SERVER["REQUEST_TIME"];
        $return['start_time'] = $good->start_time;
        $return['end_time'] = $good->end_time;
        $return['listorder'] = $good->listorder;
        $return['goods_id'] = $good->goods_id;
        $return['detail_url'] = $good->detail_url;
        $return['click_url'] = $good->click_url;
        $return['goods_name'] = $good->goods_name;
        if ($good->cat_id > 0) {
            $return['cat_name'] = $cats[$good->cat_id]['cat_name'];
        } else {
            $return['cat_name'] = "其他";
        }

        $return['item_type'] = $good->item_type;
        $return['good_shoptype'] = $good->item_type == 0 ? "淘宝" : "天猫";
        if (empty($good->click_url)) {
            $return['good_url'] = $good->detail_url;
        } else {
            $return['good_url'] = $good->click_url;
        }
        $return['cat_id'] = $good->cat_id;
        $return['cat_url'] = Yii::app()->createUrl('/front/index/index', array('cid' => $good->cat_id));
        $return['is_stock'] = $good->is_stock;
        $return['product_id'] = $good->product_id;
        $return['sales'] = $good->sales;
        $return['is_format'] = $good->is_format;
        if ($good->is_stock) {
            $return['sales_str'] = "<span>已售完</span>";
        } else {
            $return['sales_str'] = "已售<span class='font-arial'>{$good->sales}</span>件";
        }
        $return['is_stock'] = $good->is_stock;

        if ($good->start_time <= $time) {
            $return['start'] = '1';
            $timer = $good->end_time - $time;
            $d = floor($timer / 86400);
            $h = floor(($timer - $d * 86400) / 3600);
            $i = floor(($timer - $d * 86400 - $h * 3600) / 60);
            $d_str = "";
            if ($d > 0) {
                $d_str = "<span class='font-arial'>{$d}</span>天";
            }
            $return['timer_str'] = " 剩：{$d_str}<span class='font-arial'>$h</span>时<span class='font-arial'>$i</span>分";
        } else {
            $return['start'] = '0';
            $timer = $good->start_time - $time;
            $d = floor($timer / 86400);
            $h = floor(($timer - $d * 86400) / 3600);
            $i = floor(($timer - $d * 86400 - $h * 3600) / 60);
            $d_str = "";
            if ($d > 0) {
                $d_str = "<span class='font-arial'>{$d}</span>天";
            }
            $return['timer_str'] = " 距开始{$d_str}<span class='font-arial'>$h</span>时<span class='font-arial'>$i</span>分";
        }

        $return['product_img'] = $good->product_img;
        $return['goods_brief'] = $good->goods_brief;
        $return['sales'] = $good->sales;
        $return['p_price'] = $good->p_price;
        $return['promo_price'] = $good->promo_price;
        $return['discount'] = "null";
        if ($good->p_price > 0) {
            $return['discount'] = round($good->promo_price / $good->p_price, 2) * 10;
        }
        return $return;
    }

    public function getGoodBYGoodId($good_id = null, $cache = true) {
        if (!isset($good_id) || (int) $good_id < 1) {
            if (isset($this->good_id) && (int) $this->good_id) {
                $good_id = $this->good_id;
            } else {
                return false;
            }
        }
        $key = "GoodsModel_getGoodBYGoodId_{$good_id}";
        if ($return = $this->modelSetCache($key, $cache)) {
            return $return;
        }
        if ($model = $this->findByPk($good_id)) {
            Yii::app()->cache->set($key, $model, 180);
            return $model;
        }
        return false;
    }

    protected function addFilterForeshow($criteria) {
        $time = $_SERVER["REQUEST_TIME"];
        $now_timestamp = strtotime(date('Y-m-d', $time)) + 36000;
        if ($time < $now_timestamp) {
            $criteria->addCondition("isyugao=0");
        }
    }

    //排序字段排序
    public function orderRandomForListorder($data) {
        if (empty($data)) {
            return array();
        }
        $return = array();
        foreach ($data as $k => $rs) {
            $newsData = array();
            foreach ($rs as $info) {
                $newsData[$info['listorder']][$info['goods_id']] = $info;
            }
            foreach ($newsData as $id => $rs) {
                shuffle($newsData[$id]);
            }
            $data[$k] = $newsData;
        }
        foreach ($data as $k => $rs) {
            foreach ($rs as $info) {
                foreach ($info as $v) {
                    $return[] = $v;
                }
            }
        }
        return $return;
    }

    //根据start_time字段，然后进行随机处理
    public function orderRandomForStartTime($data) {
        if (empty($data)) {
            return array();
        }
        $return = array();
        $newsData = array();
        foreach ($data as $rs) {
            $newsData[$rs['start_time']][$rs['goods_id']] = $rs;
        }
        krsort($newsData);
        return $this->orderRandomForListorder($newsData);
    }

}
